package com.xin.data.simbapesa.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.Uri;
import android.provider.Settings;
import android.text.Html;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.tbruyelle.rxpermissions3.RxPermissions;
import com.xin.data.simbapesa.R;
import com.xin.data.simbapesa.adapter.PermissionDesAdapter;
import com.xin.data.simbapesa.api.PU;
import com.xin.data.simbapesa.api.U;
import com.xin.data.simbapesa.base.BaseActivity;
import com.xin.data.simbapesa.base.BaseDialog;
import com.xin.data.simbapesa.databinding.SimbaPermisssionActivityBinding;
import com.xin.data.simbapesa.obj.PermissionDesInfo;
import com.xin.data.simbapesa.utils.NumUtils;
import com.xin.data.simbapesa.utils.OrderUtils;
import com.xin.data.simbapesa.utils.ResUtils;
import com.xin.data.simbapesa.utils.SpUtils;
import com.xin.data.simbapesa.utils.ViewUtils;
import com.xin.data.simbapesa.view.SimbaSpaceItemDecoration;

import java.util.ArrayList;
import java.util.List;

public class SimbaPermissionDesActivity extends BaseActivity<SimbaPermisssionActivityBinding> {


    PermissionDesAdapter adapter;
    List<PermissionDesInfo> dataList;

    private final int MY_PERMISSIONS_REQUEST_WRITE_STORAGE = 1;

    private final int SETTINGS_REQUEST_CODE = 100;


    @Override
    protected SimbaPermisssionActivityBinding initViewBinding(LayoutInflater inflater) {
        return SimbaPermisssionActivityBinding.inflate(inflater);
    }

    @Override
    protected void initView() {

        binding.getRoot().setPadding(0, 0, 0, 0);
        setStatusBarHeight2(binding.tvRoot, ResUtils.d(R.dimen.dp_12), ResUtils.d(R.dimen.dp_12), ResUtils.d(R.dimen.dp_12));

        binding.tvHit.setText(Html.fromHtml(ResUtils.s(R.string.permission_des_hit)));

        dataList = new ArrayList<>();
        LinearLayoutManager manager = new LinearLayoutManager(this);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        binding.recyclerView.setLayoutManager(manager);
        int d = ResUtils.d(R.dimen.dp_4);
        binding.recyclerView.addItemDecoration(new SimbaSpaceItemDecoration(d / 2, d, this));
        adapter = new PermissionDesAdapter(dataList);
        binding.recyclerView.setAdapter(adapter);
        binding.tvCs.setOnClickListener(v -> {
            ViewUtils.viewScale(v);
            PU.userBuriedPoint(PU.P137, "");
            startActivity(new Intent(getActivity(), SimbaCustomerServiceActivity.class));
        });
        binding.tvBk.setOnClickListener(v -> {
            ViewUtils.viewScale(v);
            finish();
        });

        binding.tvOk.setOnClickListener(new View.OnClickListener() {
            @SuppressLint("CheckResult")
            @Override
            public void onClick(View v) {
                ViewUtils.viewScale(v);
                PU.userBuriedPoint(PU.P4, "");
                if (binding.tvBox.isChecked()) {
                    RxPermissions rxPermissions = new RxPermissions(getActivity());
                    rxPermissions.requestEachCombined("android.permission.READ_SMS")
                            .subscribe(permission -> {
                                if (permission.granted) {
                                    permissionOk();
                                } else if (permission.shouldShowRequestPermissionRationale) {
                                    permissionCancel();
                                } else {
                                    new AlertDialog.Builder(getActivity())
                                            .setTitle(getResources().getString(R.string.permisions_setting_title))
                                            .setMessage(getResources().getString(R.string.permisions_setting_subtitle))
                                            .setPositiveButton(getResources().getString(R.string.setting_btn1), (d, w) -> openSystemSettings(getActivity()))
                                            .setNegativeButton(getResources().getString(R.string.setting_btn2), null)
                                            .show();
                                }
                            });
                } else {
                    showDialog();
                }
            }
        });
        binding.tvCancel.setOnClickListener(v -> {
            ViewUtils.viewScale(v);
            PU.userBuriedPoint(PU.P3, "");
            permissionCancel();
        });

    }

    @Override
    protected void initData() {

        UP_TYPE1 = PU.P135;
        UP_TYPE2 = PU.P136;


        int maxAmout = (int) NumUtils.str2Double(SpUtils.get_string(this, SpUtils.KEY_CASH_AMOUNT, ""));


        PermissionDesInfo p1 = new PermissionDesInfo();
        p1.setMaxAmout(maxAmout);
        p1.setName(ResUtils.s(R.string.permission_title1));
        p1.setIcon(R.mipmap.des_icon1);
        p1.setContent(ResUtils.s(R.string.permission_subtitle1));
        int dmout1 = (int) (maxAmout * 0.15);
        p1.setRate(0.30);
        p1.setAmount(dmout1);


        PermissionDesInfo p2 = new PermissionDesInfo();
        p2.setMaxAmout(maxAmout);
        p2.setName(ResUtils.s(R.string.permission_title2));
        p2.setIcon(R.mipmap.des_icon3);
        p2.setContent(ResUtils.s(R.string.permission_subtitle2));
        int dmout2 = (int) (maxAmout * 0.05);
        p2.setRate(0.10);
        p2.setAmount(dmout2);

        PermissionDesInfo p3 = new PermissionDesInfo();
        p3.setMaxAmout(maxAmout);
        p3.setName(ResUtils.s(R.string.permission_title3));
        p3.setIcon(R.mipmap.des_icon2);
        p3.setContent(ResUtils.s(R.string.permission_subtitle3));
        int dmout3 = (int) (maxAmout * 0.05);
        p3.setRate(0.10);
        p3.setAmount(dmout3);

        PermissionDesInfo p4 = new PermissionDesInfo();
        p4.setMaxAmout(maxAmout);
        p4.setName(ResUtils.s(R.string.permission_title4));
        p4.setIcon(R.mipmap.des_icon4);
        p4.setContent(ResUtils.s(R.string.permission_subtitle4));
        int dmout4 = (int) (maxAmout * 0.05);
        p4.setRate(0.10);
        p4.setAmount(dmout4);

        PermissionDesInfo p5 = new PermissionDesInfo();
        p5.setMaxAmout(maxAmout);
        p5.setName(ResUtils.s(R.string.permission_title5));
        p5.setIcon(R.mipmap.des_icon5);
        p5.setContent(ResUtils.s(R.string.permission_subtitle5));
        int dmout5 = (int) (maxAmout * 0.05);
        p5.setRate(0.10);
        p5.setAmount(dmout5);

        PermissionDesInfo p6 = new PermissionDesInfo();
        p6.setMaxAmout(maxAmout);
        p6.setName(ResUtils.s(R.string.permission_title6));
        p6.setIcon(R.mipmap.des_icon6);
        p6.setContent(ResUtils.s(R.string.permission_subtitle6));
        int dmout6 = (int) (maxAmout * 0.05);
        p6.setRate(0.10);
        p6.setAmount(dmout6);

        PermissionDesInfo p7 = new PermissionDesInfo();
        p7.setMaxAmout(maxAmout);
        p7.setName(ResUtils.s(R.string.permission_title7));
        p7.setIcon(R.mipmap.des_icon7);
        p7.setContent(ResUtils.s(R.string.permission_subtitle7));
        int dmout7 = (int) (maxAmout * 0.05);
        p7.setRate(0.10);
        p7.setAmount(dmout7);



        dataList.add(p1);
        dataList.add(p2);
        dataList.add(p3);
        dataList.add(p4);
        dataList.add(p5);
        dataList.add(p6);
        dataList.add(p7);


        adapter.updateAllData();


    }

    void showDialog() {
        showTipsDialog("", "", "", ResUtils.s(R.string.permisions_agreed_tips), false, new BaseDialog.BtnClickListener() {
            @Override
            public void btnOnClickOk() {
                binding.tvBox.setChecked(true);
                ActivityCompat.requestPermissions(getActivity(), new String[]{"android.permission.READ_SMS"}, MY_PERMISSIONS_REQUEST_WRITE_STORAGE);
            }

            @Override
            public void btnOnClickCancel() {

            }

            @Override
            public void btnOnClickColse() {

            }
        });
    }

    void permissionCancel() {
        if (binding != null) {

            binding.btnLayout1.setVisibility(View.GONE);
            binding.btnLayout2.setVisibility(View.VISIBLE);

            binding.tvBtn.setText(ResUtils.s(R.string.permission_des_btn4));
            binding.tvBtn.setTextColor(Color.parseColor("#F85858"));
            binding.tvBtn.setCompoundDrawablesWithIntrinsicBounds(R.mipmap.des_icon8, 0, 0, 0);
            binding.btnLayout2.setBackground(ResUtils.de(R.drawable.des_item_btn2));
            SpUtils.save_int(getActivity(), SpUtils.KEY_SMS_PERMISSION, 2);

            toHome();

        }
    }

    void permissionOk() {
        if (binding != null) {

            binding.tvBox.setChecked(true);

            binding.btnLayout1.setVisibility(View.GONE);
            binding.btnLayout2.setVisibility(View.VISIBLE);

            binding.tvBtn.setText(ResUtils.s(R.string.permission_des_btn3));
            binding.tvBtn.setTextColor(Color.parseColor("#13C655"));
            binding.tvBtn.setCompoundDrawablesWithIntrinsicBounds(R.mipmap.des_icon9, 0, 0, 0);
            binding.btnLayout2.setBackground(ResUtils.de(R.drawable.des_item_btn1));

            SpUtils.save_int(this, SpUtils.KEY_SMS_PERMISSION, 1);

            toHome();


        }
    }

    void toHome() {


        boolean isAllAction = ContextCompat.checkSelfPermission(this, "android.permission.READ_SMS") == PackageManager.PERMISSION_GRANTED;

        if (isAllAction) {

            PU.sendDevice();

            if (!TextUtils.isEmpty(U.URL_TOKEN)) {
                userProcess(() -> {
                    boolean isCheckSteps = checkSteps();
                    if (!isCheckSteps) {
                        int state = OrderUtils.getOrderStatus();
                        if (state <= 0) {
                            startActivity(new Intent(getActivity(), SimbaApplyActivity.class));
                        } else {
                            startActivity(new Intent(getActivity(), SimbaHomeActivity.class));
                        }
                    }

                    finish();
                }, true);
            } else {
                startActivity(new Intent(this, SimbaLoginActivity.class));
                finish();
            }
        } else {
            if (!TextUtils.isEmpty(U.URL_TOKEN)) {
                startActivity(new Intent(this, SimbaHomeActivity.class));
            } else {
                startActivity(new Intent(this,SimbaLoginActivity.class));
            }
            finish();
        }

    }

    void openSystemSettings(Activity context) {
        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        Uri uri = Uri.fromParts("package", context.getPackageName(), null);
        intent.setData(uri);
        context.startActivityForResult(intent, SETTINGS_REQUEST_CODE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == SETTINGS_REQUEST_CODE) {
            toHome();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == MY_PERMISSIONS_REQUEST_WRITE_STORAGE) {
            if (grantResults.length > 0) {
                for (int grantResult : grantResults) {
                    if (grantResult == PackageManager.PERMISSION_GRANTED) {
                        permissionOk();
                        break;
                    }
                }
            } else {
                permissionCancel();
            }
        }
    }



}
